/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package graficotestearquivo2;

import graficotestearquivo.LineChartDemo2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.InputMismatchException;
import java.util.Scanner;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

/**
 *
 * @author saulomedeiros
 */
public class principal extends javax.swing.JFrame {
    private static int idparameter;
    /**
     * Creates new form principal
     */
    public principal() {
        initComponents();
    }
    public static int getIdparameter(){
        return principal.idparameter;
    }
      public static void InserirPiechart(String linha, int cont){// inserir no banco de dados
                PreparedStatement ps = null;
                Connection conn = null;
                Statement st = null;
                Scanner teclado=new Scanner(System.in);
                try{
                     DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                     conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                     ps = conn.prepareStatement("insert into piechartdata (idparameter,idpiece,piecevalue) VALUES (?,?,?) ");
                     st=conn.createStatement();
                     ResultSet rs=st.executeQuery("select max(idparameter) from parameter");
                     while(rs.next()){
                        idparameter=rs.getInt(1);
                     }
                                System.out.print("\nidparameter:");
                                ps.setInt(1, idparameter);
                                System.out.print("\nidpiece:");
                                ps.setInt(2, cont);
                                System.out.print("\npiecevalue:");
                                ps.setString(3,linha);
                                ps.executeUpdate();
                        
                 }catch(InputMismatchException e){
                     System.out.println(e.getMessage());
                 }catch(SQLException e){
                     System.out.println(e.getMessage());
                 }finally{
                    try {
                        ps.close();
                        st.close();
                        conn.close();
                    } catch (SQLException ex) {
                        System.out.println(ex.getMessage());
                    }

                 }
        }
        public static PieDataset LerDoBanco(int qntelementos,int execution){//serve como create dataset e ler do banco
            String[] parts;
            Double[] partsdouble= new Double[2];
            String[] partstring=new String[2];
            int num;
            try{    
                    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                    Statement st = conn.createStatement();
                    num=principal.getIdparameter()-qntelementos+execution+1;
                    System.out.println("subtracao torta:"+num);
                    ResultSet rs = st.executeQuery("select * from piechartdata  where idparameter="+num);
                    while(rs.next()){
                        String value = rs.getString(4);
                        parts = value.split(",");
                        if(rs.getInt(3)%2==0){
                            partsdouble[0]=Double.parseDouble(parts[0]);
                             partstring[0]=parts[1];
                        }else{
                             partsdouble[1]=Double.parseDouble(parts[0]);
                             partstring[1]=parts[1];
                        }
                        
                       
                    }         
            }catch(SQLException e){
                e.printStackTrace();
            }    
            DefaultPieDataset dataset = new DefaultPieDataset();
            dataset.setValue(partstring[1],new Double(partsdouble[1]));
            dataset.setValue(partstring[0],new Double(partsdouble[0]));    
            return dataset;
        }
        private PieDataset createDataset(String txt) {
                int cont=0; 
                String[] parts;
                //BufferedReader br=null;
                //int j=0;
                Double[] partsdouble= new Double[4];
                String[] partstring=new String[4];
                /*try {
                        br = new BufferedReader(new FileReader("setor.txt")); 
                        StringBuilder sb = new StringBuilder();
                        String line = br.readLine();
                        while (line != null) {
                        sb.append(line);
                        sb.append("\n");
                        line = br.readLine();
                    }
                 String everything = sb.toString();
                 parts = everything.split(",");*/
                try {  
			   File arquivo = new File(txt);  
			   FileInputStream   fileInputStream = new FileInputStream(arquivo);  
			   InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);  
			   LineNumberReader  lineNumberReader= new LineNumberReader(inputStreamReader);
                           StringBuilder sb = new StringBuilder();
			   String linha;  
			   

			   while(lineNumberReader.ready()) {  
				   int ln = lineNumberReader.getLineNumber();
				   linha = lineNumberReader.readLine(); 
				   if( ln>=33 && ln<=34){
                                           sb.append(linha);
                                           cont++;
                                           InserirPiechart(linha,cont);
                                           //sb.append("\n");
					   System.out.println("linha-grafico de setor:"+ln);
					   System.out.println(linha);  
				   }   
			   }
                           
                            String everything = sb.toString();
                            parts = everything.split(",");
                            partstring[1]=parts[1];
                            partstring[3]=parts[3]; 
                            partsdouble[0]=Double.parseDouble(parts[0]);
                            partsdouble[2]=Double.parseDouble(parts[2]);
                 }catch(FileNotFoundException e){
                        System.out.println(e.getMessage());
                 }catch(IOException e){
                        System.out.println(e.getMessage());
                 } 
               
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue(partstring[1],new Double(partsdouble[0]));
        dataset.setValue(partstring[3],new Double(partsdouble[2]));
        //dataset.setValue(partstring[2],new Double(partsdouble[2]));
        //dataset.setValue(partstring[3],new Double(partsdouble[3]));
        
        return dataset;
    }
    public JPanel criaGrafico1(int num1,int numero) {
        PieDataset cds = LerDoBanco(num1,numero);
        String titulo = "Gráfico de setor";
        String eixoy = "Valores";
        String txt_legenda = "Legenda:";
        boolean legenda = true;
        boolean tooltips = true;
        boolean urls = true;
         
        JFreeChart graf = ChartFactory.createPieChart(titulo, cds,  legenda, tooltips, urls);
        ChartPanel myChartPanel = new ChartPanel(graf, true);
        //myChartPanel.setHorizontalAxisTrace(urls);
        //myChartPanel.setHorizontalTraceLine(java.awt.geom.Line2D);
        
        /*myChartPanel.setSize(jPanel1.getWidth(),jPanel1.getHeight());
        myChartPanel.setVisible(true);
        jPanel1.removeAll();
        jPanel1.add(myChartPanel);
        jPanel1.revalidate();
        jPanel1.repaint();*/
        return myChartPanel;
    }  
    public JPanel criaGrafico1() {
        //Scanner teclado=new Scanner(System.in);
        //System.out.print("digite o nome do arquivo para setor:");
        PieDataset cds = createDataset("arquivo01.txt");
        String titulo = "Gráfico de setor";
        String eixoy = "Valores";
        String txt_legenda = "Legenda:";
        boolean legenda = true;
        boolean tooltips = true;
        boolean urls = true;
         
        JFreeChart graf = ChartFactory.createPieChart(titulo, cds,  legenda, tooltips, urls);
        ChartPanel myChartPanel = new ChartPanel(graf, true);
        //myChartPanel.setHorizontalAxisTrace(urls);
        //myChartPanel.setHorizontalTraceLine(java.awt.geom.Line2D);
        
        /*myChartPanel.setSize(jPanel1.getWidth(),jPanel1.getHeight());
        myChartPanel.setVisible(true);
        jPanel1.removeAll();
        jPanel1.add(myChartPanel);
        jPanel1.revalidate();
        jPanel1.repaint();*/
        return myChartPanel;
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 190, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(104, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables


}
